<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use UploadService;

class UploadController extends Controller
{
    /**
     * 文件上传
     * @param Request $request
     * @return void
     */
    public function upload(Request $request)
    {
//       使用mimetypes验证文件类型时，需要在验证规则后面添加文件类型，否则会报错
        $request->validate(['file' => ['required', 'mimetypes:image/jpeg,image/png,image/jpg,video/mpeg,video/mp4,video/x-ms-wmv,video/webm'],[
            "file.required" => "请上传文件",
            "file.mimetypes" => "文件类型不正确",
        ]]);

        return UploadService::local($request->file);
    }


    public function uploadImages(Request $request)
    {
        $request->validate(['img' => ['required', 'mimes:jpeg,png,jpg,mp3,mp4', 'max:20000'], [
            "img.required" => "请上传文件",
            "img.mimes" => "文件类型不正确",
            "img.max" => "文件大小不能超过20M",
        ]]);
        return UploadService::imagesUpload($request->img);
    }

    /**
     * wangEditor编辑器上传图片
     * @param Request $request
     * @return void
     */
    public function wangEditor(Request $request)
    {
        $request->validate(['file' => ['required', 'mimes:jpeg,jpg,bmp,png']]);
        $file = UploadService::local($request->file);
        return [
            'errno' => 0,
            'data' => [
                ['url' => $file['path'], 'alt' => $file['name'], 'href' => $file['path']]
            ]
        ];
    }

    /**
     * wangEditor编辑器上传微信图文消息图片
     * @param Request $request
     * @param WeChat $wechat
     * @param Houdunwang\WeChat\Material $material
     * @return string|false
     */
    public function wangEditorMaterialNewsUpload(Request $request, WeChat $wechat, Material $material)
    {
        $request->validate(['file' => ['required', 'mimes:jpeg,jpg,bmp,png']]);
        $file = UploadService::make($request->file);
        $image = $material->config($wechat)->uploadNewsImage($file['path']);
        return \json_encode([
            'errno' => 0,
            'data' => [$image['url']],
        ]);
    }
}
